package com.maddox.relax.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.maddox.relax.R
import com.maddox.relax.databinding.ActivityBluetoothListBinding
import com.maddox.relax.util.LogUtil

/**
 * @author Maddox
 * 蓝牙设备列表
 */
class BluetoothListActivity : AppCompatActivity() {

    private val REQUEST_CODE = 123
    lateinit var bluetoothAdapter: BluetoothAdapter
    lateinit var bluetoothListAdapter: BluetoothListAdapter
    lateinit var bd:ActivityBluetoothListBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = DataBindingUtil.setContentView(this,R.layout.activity_bluetooth_list)
        initView()
    }

    private fun initView() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "该设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        bd.header.toolbarTitle.text = "设备列表"
        bd.header.toolbarBack.setOnClickListener {
            finish()
        }
        bd.smartrefresh.setOnRefreshListener {
            if (bluetoothAdapter.isDiscovering)
                bluetoothAdapter.cancelDiscovery()
            //刷新列表
            getBluetoothList()
            bd.smartrefresh.finishRefresh(1000)
        }
        bluetoothListAdapter = BluetoothListAdapter(null)
        bd.recyclerview.layoutManager = LinearLayoutManager(this)
        bd.recyclerview.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        bd.recyclerview.adapter = bluetoothListAdapter
        bluetoothListAdapter.setOnItemClickListener { adapter, view, position ->
            //进行连接
            var item = bluetoothListAdapter.getItem(position)
            buildConnect(item)
        }
        //注册监听
        registBlueReceiver()
        if (bluetoothAdapter.isEnabled) {
            getBluetoothList()
        } else {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableIntent, REQUEST_CODE)
        }
    }

    private fun registBlueReceiver() {
        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(blueReceiver, filter)
    }

    private fun getBluetoothList() {
        bluetoothListAdapter.data.clear()
        bluetoothListAdapter.notifyDataSetChanged()
        //发现设备
        bluetoothAdapter.startDiscovery()
    }

    //设备扫描以及各种状态监听器
    private val blueReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action

            when (action) {
                //蓝牙状态
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    //蓝牙 当前状态
                    val newAction = intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                    //蓝牙 上一个状态
                    val previousAction =
                        intent?.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1)
                    if (newAction == BluetoothAdapter.STATE_ON) {
                        //已打开蓝牙
                        LogUtil.d("已打开蓝牙")
                    } else if (newAction == BluetoothAdapter.STATE_OFF) {
                        //已关闭蓝牙
                        LogUtil.d("已关闭蓝牙")
                        if (bluetoothAdapter.isDiscovering) bluetoothAdapter.cancelDiscovery()
                    }
                }

                //开始扫描
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    Toast.makeText(context, "开始扫描", Toast.LENGTH_SHORT).show()
                    LogUtil.d("搜索蓝牙设备开始")
                }
                //扫描结束
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    LogUtil.d("搜索蓝牙设备结束")
                }
                //发现新设备
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
                    var deviceName = device.name
                    if (deviceName == null) deviceName = "未命名"
                    LogUtil.d("发现设备$deviceName")
                    bluetoothListAdapter.addData(device)
                }
                //绑定设备
                BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                    //获取要绑定的设备
                    val boundDevice =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
                    when (boundDevice.bondState) {
                        //正在绑定
                        BluetoothDevice.BOND_BONDING -> {
                            Toast.makeText(context, "正在配对 ${boundDevice.name}", Toast.LENGTH_SHORT)
                                .show()
                            LogUtil.d("正在配对 ${boundDevice.name}")
                        }
                        BluetoothDevice.BOND_BONDED -> {
                            Toast.makeText(context, "配对完成 ${boundDevice.name}", Toast.LENGTH_SHORT)
                                .show()
                            LogUtil.d("配对完成 ${boundDevice.name}")
                        }
                        BluetoothDevice.BOND_NONE -> {
                            Toast.makeText(context, "取消配对 ${boundDevice.name}", Toast.LENGTH_SHORT)
                                .show()
                            LogUtil.d("配对完成 ${boundDevice.name}")
                        }

                    }

                }


            }

        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            //turn bluetooth successfully
            getBluetoothList()
        } else if (requestCode == REQUEST_CODE && resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "未开启蓝牙功能,无法使用", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "当前设备无法被检测到", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消注册以及设备扫描
        unregisterReceiver(blueReceiver)
        if (bluetoothAdapter.isDiscovering)
            bluetoothAdapter.cancelDiscovery()
    }

    //构建连接
    private fun buildConnect(item: BluetoothDevice) {
        //关闭扫描新设备
        if (bluetoothAdapter.isDiscovering)
            bluetoothAdapter.cancelDiscovery()

        if (item.bondState != BluetoothDevice.BOND_BONDED) {
            item.createBond()
            return
        }
        //跳转到客户端页面
        val intent = Intent(this, BluetoothClientActivity::class.java)
        intent.putExtra("device", item)
        startActivity(intent)
    }


    //将当前设备处于可检测时间设置为10分钟
    private fun makeDeviceDiscover() {
        val discoverableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE).apply {
            putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600)
        }
        startActivity(discoverableIntent)
    }


}